package com.northpool.operator.platform.datacenter;

import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(
        ref = "GetTableIdOperator",
        name = "数据中心",
        version = "数据ID获取",
        description = "获取数据中心的数据表ID"
)
@OutputParams({
        @OutputParam(ref = "tableId", name = "数据ID", type = TypeEnum.STRING)
})
public class GetTableIdOperator extends StpOperatorHelper {
    final String SERVER_URL = "%s/datahub/database/connection/getTableIdBySourceAndTableName?sourceId=%s&tableName=%s";

    @InputParams({
            @InputParam(ref = "serviceUrl", name = "服务地址", desc = "平台服务地址，如: http://192.168.164.45:8021", required = true),
            @InputParam(ref = "dataSourceId", name = "数据源ID", desc = "数据源ID，如：402881ac95b269d50195b26e7b2600e0", type = TypeEnum.DATASOURCE, required = true),
            @InputParam(ref = "tableName", name = "数据表名称", desc = "数据表名称，如: public.table", required = true),
    })
    public GetTableIdOperator() {
    }

    protected String dataSourceId;
    protected String serviceUrl;
    protected String tableName;

    @Override
    public void execute(ParamTool params) throws Exception {
        // 1.发布数据服务
        serviceUrl = params.getStr("serviceUrl");
        dataSourceId = params.getStr("dataSourceId");
        tableName = params.getStr("tableName");

        String schema = "public";
        if (tableName.contains(".")) {
            String[] split = tableName.split("\\.");
            schema = split[0];
            tableName = split[1];
        }

        String tableListUrl = String.format(SERVER_URL, serviceUrl, dataSourceId, tableName);
        try (
            HttpResponse execute = HttpUtil.createGet(tableListUrl)
                    .timeout(60000).execute();
        ) {
            if (!execute.isOk()) {
                Console.error("获取数据中心表ID请求失败: {}, 请求地址: {}", execute, tableListUrl);
                throw new RuntimeException("请求失败");
            }
            String body = execute.body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            JSONArray dataArr = jsonObject.getJSONArray("data");
            if (dataArr == null || dataArr.isEmpty()) {
                throw new RuntimeException("未找到数据表：" + tableName);
            }
            String tableId = "";
            for (Object obj : dataArr) {
                JSONObject item = (JSONObject) obj;
                if (schema.equals(item.getString("schema"))) {
                    tableId = item.getString("id");
                    break;
                }
            }
            this.result("tableId", tableId);
        } catch (Exception ex) {
            Console.error("获取数据中心表ID请求失败: {}\n 请求地址: {}", ex.getMessage(), tableListUrl);
        }
    }
}
